<?php
/*
 * Created on Feb 7, 2010
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 	$title = 'Quản lí bất động sản';
 	include('../includes/session.php');
	if($session->logged_in){
		if($session->userlevel == 1){
			header("Location: ../index.php");
		}
	}else{
		header("Location: login.php");
	}
	include('../includes/encrypturl.php');
	include('../models/cityregion_model.php');
	include('../models/transaction_model.php');
	include('../models/realestate_model.php');
	include('../models/reesnew_model.php');
	$session->setHeader(8);	
 	include('../includes/header.inc');
	echo '<script type="text/javascript" src="../js/prototype-1.6.0.2.js"></script>';
	
	if (isset($_GET['SelectedRees'])){
		$SelectedRess =strtoupper($_GET['SelectedRees']);
	} elseif(isset($_POST['SelectedRees'])){
		$SelectedRess =strtoupper($_POST['SelectedRees']);
	}
	
	echo '<div id="wrapper">';
	echo '<div id="content">';
	echo '<div id="box">';	
	
	if (isset($_GET['delete']) && $SelectedRess) {
		if($reesNewModel->deleteRees($SelectedRess) == 0){
			echo prnMsg(_('Thông tin BĐS < '.$SelectedRess.' > đã xóa.'),'success');
		}else{
			echo prnMsg(_('Thông tin BĐS < '.$SelectedRess.' > chưa xóa.'),'success');
		}				
		unset ($SelectedRess);
		unset($delete);
	}
	
	if (!isset($SelectedRess)) {
		
		$start=$_GET['start'];
		if(strlen($start) > 0 and !is_numeric($start)){
			echo "Data Error";
			exit;
		}		
		
		$eu = ($start - 0); 
		$limit = $number_record_perpage;                                 
		$this1 = $eu + $limit; 
		$back = $eu - $limit; 
		$next = $eu + $limit;
				
		$num = $reesNewModel->getCountItems();
		$result = $reesNewModel->getTopItems($eu, $limit);
		
	    echo '<h3>Danh sách Bất động sản</h3>';
		echo '<table width="100%"><thead>';
			echo '<tr class="borderBottom">';
	        echo '<th><a href="#">ID<img src="'.$PathPrefix.'img/icons/arrow_down_mini.gif" width="16" height="16" align="absmiddle" /></a></th>';
	        echo '<th><a href="#">Tiêu đề</a></th>';     
	        echo '<th><a href="#">Liên hệ</a></th>';
			echo '<th><a href="#">Giá bán/thuê</a></th>';
			echo '<th><a href="#">Đặt biệt</a></th>';
			echo '<th><a href="#">Lượt xem</a></th>';
	        echo '<th><a href="#">Ngày tạo</a></th>';
			echo '<th><a href="#">Ngày cập nhật</a></th>';
			echo '<th><a href="#">Ngày hết hạn</a></th>';
	        echo '<th><a href="#">Hành động</a></th>';
	        echo '</tr></thead>';
			while ($myrow = $reesNewModel->getArrayNameItem($result)){
				printf('<tbody><tr class="borderBottom">
						<td class="a-center">%s</td>						
	                    <td>%s</td>
	                    <td>%s</td>
	                    <td>%s</td>
						<td>%s</td>
						<td>%s</td>
	                    <td>%s</td>	
						<td>%s</td>
						<td>%s</td>
	                    <td><a href="%sSelectedRees=%s"><img src="'.$PathPrefix.'img/icons/user_edit.png" title="Cập nhật BĐS" width="16" height="16" /></a>
							<a href="%sSelectedRees=%s&delete=1"><img src="'.$PathPrefix.'img/icons/user_delete.png" title="Xóa BĐS" width="16" height="16" /></a></td>
	                    </tr></tbody>',
						$myrow['id'],
						$myrow['title'],
						$myrow['contact'],
						$myrow['price'],
						$myrow['isSpecial'],
						$myrow['showNo'],
						ConvertSQLDate($myrow['createDate']),
						ConvertSQLDate($myrow['updateDate']),
						ConvertSQLDate($myrow['endDate']),	
						$_SERVER['PHP_SELF'] . '?' . SID . '&',
						$myrow['id'],
						$_SERVER['PHP_SELF'] . '?' . SID . '&',
						$myrow['id']);				
			}			
		echo '</table>';
		if($num > $limit ){
			echo '<div id="pager">Trang ';
			if($back >=0) {  
				echo '<a href="'.$_SERVER['PHP_SELF'].'?start='.$back.'"><img src="'.$PathPrefix.'img/icons/arrow_left.gif" width="16" height="16" /></a>';
			};
			$i=0;
			$l=1;
			for($i=0;$i < $num;$i=$i+$limit){
				if($i <> $eu){
					echo " <a href='".$_SERVER['PHP_SELF']."?start=$i'><font face='Verdana' size='2'>$l</font></a> ";
				}
				else { 
					echo "<font face='Verdana' size='4' color=red>$l</font>";				
				}
					$l=$l+1;
			}
			if($this1 < $num) {
				echo '<a href="'.$_SERVER['PHP_SELF'].'?start='.$next.'"><img src="'.$PathPrefix.'img/icons/arrow_right.gif" width="16" height="16" /></a>';
			};
            
            echo ' Tổng cộng <strong>'.$num.'</strong> bất động sản
                    </div>';
		}else{
			echo '<div id="pager">Tổng cộng <strong>'.$num.'</strong> bất động sản</div>';
		}
	}
	
	if (isset($SelectedRess)) {
		echo "<div><a href='" . $_SERVER['PHP_SELF'] . '?' . SID . "'><font face='Verdana' size='2' color=red>" . _('Quay về danh sách Bất động sản') . "</font></a></div>";
	}
	echo '</div>';
	echo '<br />';
	echo '<div id="box">';
	
	if(isset($_SESSION['success'])){
	   /* Registration was successful */
	   if($_SESSION['success']){
	   		echo prnMsg(_('Bất động sản < '.$_SESSION['successname'].' > đã tạo thành công.'),'success');
	   }
	   /* Registration failed */
	   else{
	      echo prnMsg(_('Bất động sản < '.$_SESSION['successname'].' > không thể tạo'),'success');
	   }
	   unset($_SESSION['success']);
	   unset($_SESSION['successname']);
	}
	
	if(isset($_SESSION['edit'])){   		
   		echo prnMsg(_('Bất động sản < '.$_SESSION['editname'].' > cập nhật thành công'),'success');
		unset($_SESSION['edit']);
		unset($_SESSION['editname']);
	}

	if($form->num_errors > 0){
		echo $form->error("title");
		echo $form->error("address");
	    echo $form->error("size");
	    echo $form->error("price");
	    echo $form->error("description");
	    echo $form->error("contact");
		echo $form->error("image");
	}
	
	echo "<form id='form' method='post' enctype='multipart/form-data' action='../controllers/reesitem_controller.php" . "?" . SID . "'>";
	
	if (isset($SelectedRess)) {
		
		$myrow = $reesNewModel->getReesById($SelectedRess);
		
		$_POST['title'] = $myrow['title'];
		$_POST['address'] = $myrow['place'];
		$_POST['size'] = $myrow['size'];
		$_POST['source'] = $myrow['source'];
		$_POST['direction'] = $myrow['direction'];
		$_POST['price'] = $myrow['price'];
		$_POST['description'] = $myrow['description'];
		$_POST['content'] = $myrow['content'];
		$_POST['contact'] = $myrow['contact'];
		$_POST['reestype'] = $myrow['rees_transaction_id'];		
		$_POST['typehouse'] = $myrow['rees_type_id'];
		$_POST['region'] = $myrow['rees_cityregion_id'];
		$_POST['city'] = $myrow['rees_city_id'];
		$_POST['district'] = $myrow['rees_district_id'];		
		$_POST['createDate'] = ConvertSQLDate($myrow['createDate']);
		$arrayEndDate = explode(' ', ConvertSQLDate($myrow['endDate']));
		$_POST['endDate'] = $arrayEndDate[0];
		$_POST['image'] = $myrow['image'];
		$_POST['isSpecial'] = $myrow['isSpecial'];
		
		echo "<input type=hidden name='SelectedRees' VALUE='" . $SelectedRess . "'>";
			
		echo '<h3 id="adduser">Cập nhật Bất động sản</h3><br/>';			
	}else{
		// khong chon select user
		echo '<h3 id="adduser">Thêm Bất động sản</h3><br/>';
	}	
	if (!isset($_POST['createDate'])){
		$_POST['createDate']= $today;
	}
	
	echo '<fieldset id="personal">';
    echo '<legend>THÔNG TIN CHUNG</legend>';
	
	echo '<label for="title">Tiêu đề<span class="require">(*)</span>: </label>
		<input name="title" id="title" type="text" tabindex="1" size="70" value="'.(isset($SelectedRess)?$_POST['title']:$form->value("title")).'"/><br />';
	echo '<label for="address">Địa chỉ<span class="require">(*)</span>: </label>
		<input name="address" id="address" type="text" tabindex="1" size="70" value="'.(isset($SelectedRess)?$_POST['address']:$form->value("address")).'"/><br />';
	echo '<label for="size">Diện tích<span class="require">(*)</span>: </label>
		<input name="size" id="size" type="text" tabindex="1" size="70" value="'.(isset($SelectedRess)?$_POST['size']:$form->value("size")).'"/> (m2)<br />';
	echo '<label for="source">Nguồn tin: </label>
		<input name="source" id="source" type="text" tabindex="1" size="70" value="'.(isset($SelectedRess)?$_POST['source']:$form->value("source")).'"/><br />';
	echo '<label for="direction">Hướng nhà: </label>
		<input name="direction" id="direction" type="text" tabindex="1" size="70" value="'.(isset($SelectedRess)?$_POST['direction']:$form->value("direction")).'"/><br />';
	echo '<label for="price">Giá bán/thuê<span class="require">(*)</span>: </label>
		<input name="price" id="price" type="text" tabindex="1" size="70" value="'.(isset($SelectedRess)?$_POST['price']:$form->value("price")).'"/> (triệu/VNĐ)<br />';
	echo '<label for="description">Mô tả<span class="require">(*)</span>: </label>';
		echo '<textarea type="text" name="description" cols="5" rows="1">'.(isset($SelectedRess)?$_POST['description']:$form->value("description")).'</textarea><br />';
	echo '<label for="content">Nội dung: </label>';
		echo '<textarea type="text" name="content" cols="5" rows="1">'.(isset($SelectedRess)?$_POST['content']:$form->value("content")).'</textarea><br />';
	echo '<label for="contact">Liên hệ - điện thoại<span class="require">(*)</span>: </label>';
		echo '<textarea type="text" name="contact" cols="5" rows="1">'.(isset($SelectedRess)?$_POST['contact']:$form->value("contact")).'</textarea><br />';
	echo '<label for="isSpecial">Đặc biệt: </label>';
		echo '<textarea type="text" name="isSpecial" cols="5" rows="1">'.(isset($SelectedRess)?$_POST['isSpecial']:$form->value("isSpecial")).'</textarea><br />';
	echo '<label for="image">Chọn ảnh: </label><input type="file" name="image"/><br />';
	
	$trans = $transactionModel->getTrans(null, null);
	echo '<label for="reestype">Loại tin<span class="require">(*)</span>: </label>';							
	echo '<select name="reestype" class="selectOneMedium" style="font-size: 11px;">';
		$reesType = (isset($SelectedRess)?$_POST['reestype']:$form->value("reestype"));
		while ($myrow = $transactionModel->getArrayNameTrans($trans)) {
			if($reesType == $myrow['id'])
				echo '<option selected="selected" value="'. $myrow['id'] .'">'. $myrow['name'] .'</option>';
			else
				echo '<option value="'. $myrow['id'] .'">'. $myrow['name'] .'</option>';
		}
	echo '</select><br />';
	$typehouse = $realestateModel->getTypes(null, null);	
	echo '<label for="typehouse">Loại nhà<span class="require">(*)</span>: </label>';
	echo '<select name="typehouse" class="selectOneMedium" style="font-size: 11px;">';
		$reesHouse = (isset($SelectedRess)?$_POST['typehouse']:$form->value("typehouse"));
		while ($myrow = $realestateModel->getArrayNameTypes($typehouse)) {
			if($reesHouse == $myrow['id'])
				echo '<option selected="selected" value="'. $myrow['id'] .'">'. $myrow['name'] .'</option>';
			else 
				echo '<option value="'. $myrow['id'] .'">'. $myrow['name'] .'</option>';
		}
	echo '</select><br />';
	$region = $cityModel->getRegions(null, null);
	echo '<label for="region">Khu đô thị:</label>';
	echo '<select name="region" class="selectOneMedium" style="font-size: 11px;">';
		echo '<option selected="selected" value="0">- Các loại khác -</option>';
		$reesRegion = (isset($SelectedRess)?$_POST['region']:$form->value("region"));
		while ($myrow = $cityModel->getArrayNameRegions($region)) {
			if($reesRegion == $myrow['id'])
				echo '<option selected="selected" value="'. $myrow['id'] .'">'. $myrow['name'] .'</option>';
			else 
				echo '<option value="'. $myrow['id'] .'">'. $myrow['name'] .'</option>';
		}
	echo '</select><br />';
	$cities = $cityModel->getCities();
	echo '<label for="city">Tỉnh/TP<span class="require">(*)</span>:</label>';
	echo '<select name="city" class="selectOneMedium" onchange="cityChange(this.value)" style="font-size: 11px;">';
		echo '<option selected="selected" value="0">- Các loại khác -</option>';
		$reesCity = (isset($SelectedRess)?$_POST['city']:$form->value("city"));
		while ($myrow = $cityModel->getArrayNameRegions($cities)) {
			if($reesCity == $myrow['id'])
				echo '<option selected="selected" value="'. $myrow['id'] .'">'. $myrow['name'] .'</option>';
			else 
				echo '<option value="'. $myrow['id'] .'">'. $myrow['name'] .'</option>';
		}
	echo '</select><br />';	
	echo '<label for="district">Quận/Huyện :</label>';
	echo '<select name="district" id ="district" class="selectOneMedium" style="font-size: 11px;">';
		echo '<option value="0">- Chọn Tỉnh/TP -</option>';
		if($reesCity > 0){
			$districts = $cityModel->getDistrictsByCity($reesCity);			
			$reesDistrict = (isset($SelectedRess)?$_POST['district']:$form->value("district"));
			while ($myrow = $cityModel->getArrayNameRegions($districts)) {
				if($reesDistrict == $myrow['id'])
					echo '<option selected="selected" value="'. $myrow['id'] .'">'. $myrow['name'] .'</option>';
				else 
					echo '<option value="'. $myrow['id'] .'">'. $myrow['name'] .'</option>';
			}
		}
	echo '</select><br />';
	
	if (!isset($SelectedRess)) {
		$createDate = (!isset($SelectedRess)?$_POST['createDate']:$form->value("createDate"));
		echo '<label for="createDate">Ngày tạo: </label><input name="createDate" id="createDate" readonly="readonly" type="text" tabindex="7" size="15" value="'.$createDate.'"/>';
		echo '<a href="javascript:NewCal(\'createDate\', \'ddmmyyyy\', false, 24, \'..\');"><img border="0" src="../img/cal.jpg" alt="" /></a><br />';
		echo '<input type="hidden" name="itemadd" value="1" />';
	}else{
		if (($_POST['image'] != null) && file_exists('../'.$_SESSION['PathUploadItem'].$_POST['image'])) {	
			echo '<label for="image">Ảnh: </label><img src="../'.$_SESSION['PathUploadItem'].$_POST['image'].'" alt="Image Content" width="'.IMAGE_WIDTH.'" height="'.IMAGE_HEIGHT.'"  /><br />';
		}else{
			echo '<label for="image">Ảnh: </label><img src="../img/NoPhotoAvailable.jpg" alt="Image Content" width="'.IMAGE_WIDTH.'" height="'.IMAGE_HEIGHT.'"  /><br />';
		}
		echo '<input type="hidden" name="itemedit" value="1" />';
	}
	echo '<input type="hidden" name="userId" value="'. $session->userid .'" />';
	
	$endDate = (isset($SelectedRess)?$_POST['endDate']:$form->value("endDate"));
	echo '<label for="endDate">Ngày hết hạn (mặc định 30 ngày):</label><input name="endDate" id="endDate" readonly="readonly" type="text" tabindex="7" size="15" value="'.$endDate.'"/>';
	echo '<a href="javascript:NewCal(\'endDate\', \'ddmmyyyy\', false, 24, \'..\');"><img border="0" src="../img/cal.jpg" alt="" /></a>';
	
	echo '</fieldset>';
	echo '<div align="center">
     		<input name="submit" type="submit" value="Đồng ý" /> 
            <input name="reset" type="reset"  value="Thiết lập lại"/>
          </div></form>';
	
	echo '</div>';
	echo '</div>';
	
	include('../includes/footer.inc');
?>
<script>
	function cityChange(value){
		var url = '../getDistrict.php?cityId=';
		new Ajax.Request(url + value,
		  {
		    method:'get',
		    onSuccess: function(transport){
				var cbxDistrict = document.getElementById('district');
				cbxDistrict.options.length = 0;
				cbxDistrict.options[0] = new Option('- Các loại khác -', 0);
				var response = transport.responseText;
				var districts = eval( "(" + response + ")");
				for(i =0 ; i < districts.length; i ++)					
					cbxDistrict.options[cbxDistrict.options.length] = new Option(districts[i]['name'], districts[i]['id']);
		    },
		    onFailure: function(){ alert('Something went wrong...') }
		  });
	}
</script>
